﻿using FastSql.Core;
using Microsoft.AspNetCore.SignalR;
using SignalrChat.Buesses;
using SignalrChat.Models;

namespace SignalrChat
{
    public class ChatHub : Hub
    {

        private UsersBll usersBll;
        /// <summary>
        /// 获取用户列表
        /// </summary>
        public static List<UsersExt> GetUsers { get { return userlist; } }


        public ChatHub()
        {
            usersBll = new UsersBll();
        }

        private static List<UsersExt> userlist = new List<UsersExt>();
        public override Task OnConnectedAsync()
        {
            var cid = this.Context.ConnectionId;
            var user = this.Context.UserIdentifier;
            return base.OnConnectedAsync();
        }
        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception? exception)
        {
            lock (userlist)
            {
                var cid = this.Context.ConnectionId;
                var user = userlist.Where(w => w.ConnectionId == cid).FirstOrDefault();
                if (user != null)
                {
                    userlist.Remove(user);
                }
            }
          
            return base.OnDisconnectedAsync(exception);
        }

        /// <summary>
        /// 发送用户
        /// </summary>
        /// <param name="user">用户帐号</param>
        /// <returns></returns>
        public async Task SendUser(string user)
        {
            var cid = this.Context.ConnectionId;
            lock (userlist)
            {
                var users = usersBll.GetUsers();
                var model = users.Where(w => w.Account == user?.Trim()).FirstOrDefault();
                if (model != null)
                {
                    var ue = model.ToMode<UsersExt>();
                    ue.ConnectionId = cid;
                    var hasmodle = userlist.Where(w => w.Account == user);
                    if (hasmodle.Any())
                    {
                        userlist.Remove(hasmodle.First());
                    }
                    userlist.Add(ue);
                }
            }
          
        }


        /// <summary>
        /// 向客户端发送消息
        /// </summary>
        /// <param name="user">用户名</param>
        /// <param name="Message">消息</param>
        /// <returns></returns>
        public async Task SendMessage(string user,string nickName, string Message)
        {

            await this.Clients.All.SendAsync("ReceiveMessage", user, nickName, Message);
        }

        /// <summary>
        /// 一对一消息发送
        /// </summary>
        /// <param name="Cid">用户连接ID</param>
        /// <param name="Message"></param>
        /// <returns></returns>
        public async Task SendMessageToUser(string Cid, string Message)
        {

            await this.Clients.Client(Cid).SendAsync(Message);
        }
    }
}
